var temper = {};

temper.regex = /{{[0-9\[\]\w\.\(\)]+}}/g;

temper.sanitize = function (str) {

	str = String(str);

	if (!str) return "";

	return str.replace(/[<>]/g,"");
}

temper.include = function (uri) {

	var req = new XMLHttpRequest();
	req.open("GET", uri, false);
	req.send();

	document.getElementsByTagName("head")[0].innerHTML += req.responseText;
}

temper.script = function (sid) {

	var t = {};

	t.script = document.getElementById(sid);

	t.xform = function (obj) {

		var str = t.script.innerText;

		if (!str) str = t.script.textContent;

		var matches = str.match(temper.regex);
		var subs = [];
		for (var i = 0; i < matches.length; i++) {
			with(obj) {
				var sub = eval(matches[i]);

				if (sub == null) throw "null value in template: " + matches[i];

				subs.push(eval(matches[i]));
			}
		}

		for (var i = 0; i < matches.length; i++) {
			str = str.replace(matches[i], subs[i]);
		}

		return str;
	}

	t.append = function (id, obj) {

		try {
			var child = document.createElement("div");
			child.innerHTML = t.xform(obj);

			var container = document.getElementById(id);
			
			if (!container) throw "missing container " + id;

			container.appendChild(child);

			return child;

		} catch (e) {
			if (console) console.log(e.message);
		}
	}

	t.replace = function (id, obj) {

		document.getElementById(id).innerHTML = t.xform(obj);
	}

	return t;
}
